package com.nativetalk.service.study.update;

import com.agora.DynamicKey4Sample;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.FoundChange.TdNtMembFoundChangeInset;
import com.nativetalk.bean.FoundChange.TdNtTeaFoundChangeInsert;
import com.nativetalk.bean.course.TdNtCoursePictureList;
import com.nativetalk.bean.course.TdNtCoursePictureListUrl;
import com.nativetalk.bean.course.TsNtCourseInfoDetail;
import com.nativetalk.bean.course.catalog.TdNtCourseCatalogEnglish;
import com.nativetalk.bean.member.TdNtMemberDetail;
import com.nativetalk.bean.member.TdNtMemberDetailOrders;
import com.nativetalk.bean.member.TdNtMemberInvite;
import com.nativetalk.bean.member.TdNtMemberStudyTimes;
import com.nativetalk.bean.member.course.TdNtMembCourseDetail;
import com.nativetalk.bean.member.setmeal.TdNtMembSetmealDetail;
import com.nativetalk.bean.member.setmeal.his.TdNtSetmealUseHisInsert;
import com.nativetalk.bean.study.TdNtStudyTeachUpdate;
import com.nativetalk.bean.teacher.TdNtTeacherIndex;
import com.nativetalk.bean.teacher.TdNtTeacherState;
import com.nativetalk.bean.website.TsNtWebSiteConfIndex;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.common.util.MemcachedKey;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.dao.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

/**
 * Created by lizhun on 16/1/12.
 */
@Service
public class  StudyTeachUpdateServiceImpl implements StudyTeachUpdateService {
    private static Logger logger = Logger.getLogger(StudyTeachUpdateServiceImpl.class);
    @Resource
    private TdNtStudyTeachDao tdNtStudyTeachDao;
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TdNtTeacherDao tdNtTeacherDao;
    @Resource
    private TdNtMembFoundChangeDao tdNtMembFoundChangeDao;
    @Resource
    private TdNtTeaFoundChangeDao tdNtTeaFoundChangeDao;
    @Resource
    private TdNtMembSetmealDao tdNtMembSetmealDao;
    @Resource
    private TdNtSetmealUseHisDao tdNtSetmealUseHisDao;
    @Resource
    private TsNtCourseInfoDao tsNtCourseInfoDao;
    @Resource
    private TdNtMembCourseDao tdNtMembCourseDao;
    static int ts = (int)(new Date().getTime()/1000);
    static int r = new Random().nextInt();
    static long uid = 2882341273L;
    static int expiredTs = 0;
    static String appID   = "612ca682ce3245a6b2b83e6dd54de535";
    @Override
    public synchronized   RetInfo eceivingOrders(int stt_id,int tea_id,int type,int version) {
        String logInfo = this.getClass().getName() + ":eceivingOrders:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            TdNtStudyTeachUpdate tdNtStudyTeachUpdate = tdNtStudyTeachDao.findTdNtStudyTeachUpdate(stt_id);
            if (tdNtStudyTeachUpdate != null && tdNtStudyTeachUpdate.getStudy_state().equals("0")) {
                if (type == 1) {
                    tdNtStudyTeachUpdate.setStudy_state("6");
                    tdNtStudyTeachUpdate.setEnd_time(new Timestamp(System.currentTimeMillis()));
                    tdNtStudyTeachDao.updateTdNtStudyTeachCancel(tdNtStudyTeachUpdate);
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("取消成功");

                } else {
                    tdNtStudyTeachUpdate.setStudy_state("1");
                    tdNtStudyTeachUpdate.setTea_id(tea_id);
                    tdNtStudyTeachUpdate.setStart_time(new Timestamp(System.currentTimeMillis()));

                    tdNtStudyTeachDao.updateTdNtStudyTeach(tdNtStudyTeachUpdate);

                    TdNtTeacherState tdNtTeacherState = new TdNtTeacherState();
                    tdNtTeacherState.setTea_id(tdNtStudyTeachUpdate.getTea_id());
                    tdNtTeacherState.setState(Constants.Teacher.State.busy);
                    tdNtTeacherState.setState_order(Constants.Teacher.StateOrder.busy);
                    TdNtMemberDetail tdNtMemberDetail = tdNtMemberDao.findTdNtMemberDetail(tdNtStudyTeachUpdate.getMemb_id());
                    MemcachedUtils.delete(tdNtMemberDetail.getToken()+"nativetalk");
                    tdNtTeacherDao.updateTdNtTeacherState(tdNtTeacherState);

                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("接单成功");
                    Map<String , List<TdNtCoursePictureList>> tdNtCoursePictureListMap = (Map<String , List<TdNtCoursePictureList>> )MemcachedUtils.get(MemcachedKey.tdNtCoursePictureListMap);
                    List<TdNtCoursePictureList> tdNtCoursePictureLists = tdNtCoursePictureListMap.get("" + tdNtStudyTeachUpdate.getCou_id());
                    List<TdNtCoursePictureListUrl> tdNtCoursePictureListUrls = new ArrayList<>();
                    for (int i = 0 ; i < tdNtCoursePictureLists.size(); i ++) {
                        TdNtCoursePictureListUrl tdNtCoursePictureListUrl = new TdNtCoursePictureListUrl();
                        tdNtCoursePictureListUrl.setImg_url(tdNtCoursePictureLists.get(i).getImg_url());
                        tdNtCoursePictureListUrls.add(tdNtCoursePictureListUrl);
                    }
                    if (version ==2) {
                        retInfo.setObj(tdNtCoursePictureLists);
                    } else {
                        retInfo.setObj(tdNtCoursePictureListUrls);
                    }
                    if (version >=3) {

                        Map<String, Object> map = new HashMap<>();
                        map.put("picture",tdNtCoursePictureLists);
                        map.put("student_channel", tdNtMemberDetail.getToken());
                        retInfo.setObj(map);
                    }

                }

            } else {
                if (type == 1){
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("已经接单"));
                    TdNtMemberDetail tdNtMember = tdNtMemberDao.findTdNtMemberDetail(tdNtStudyTeachUpdate.getMemb_id());
                    Map<String, Object> result = new HashMap<>();
                    result.put("memb_name",tdNtMember.getMemb_name());
                    result.put("memb_head_portrait",tdNtMember.getMemb_head_portrait());
                    result.put("stt_id", stt_id);
                    TdNtTeacherIndex tdNtTeacherIndex =  tdNtTeacherDao.findTdNtTeacherIndex(tdNtStudyTeachUpdate.getTea_id());
                    result.put("tea_name", tdNtTeacherIndex.getTea_name());
                    result.put("tea_head_portrait", tdNtTeacherIndex.getTea_head_portrait());
                    Map<String , List<TdNtCoursePictureList>> tdNtCoursePictureListMap = (Map<String , List<TdNtCoursePictureList>> )MemcachedUtils.get(MemcachedKey.tdNtCoursePictureListMap);
                    result.put("course_pictures", tdNtCoursePictureListMap.get("" + tdNtStudyTeachUpdate.getCou_id()));
                    result.put("channel",tdNtTeacherIndex.getTea_invite_code());
                    result.put("recordKey", DynamicKey4Sample.getRecordKey(appID,tdNtTeacherIndex.getTea_invite_code(),ts, r, uid, expiredTs));
                    result.put("channelKey", DynamicKey4Sample.getChannelKey(appID,tdNtTeacherIndex.getTea_invite_code(),ts, r, uid, expiredTs));
                    result.put("ts", ts);
                    result.put("r", r);
                    result.put("uid", uid);
                    result.put("appID", appID);
                    result.put("expiredTs", expiredTs);
                    retInfo.setObj(result);
                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("STUDYTEACH_STATE.ERROR"));
                }

            }


        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
    @Override
    public synchronized   RetInfo eceivingOrdersThree(int stt_id,int tea_id,int type,int version) {
        String logInfo = this.getClass().getName() + ":eceivingOrders:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            TdNtStudyTeachUpdate tdNtStudyTeachUpdate = tdNtStudyTeachDao.findTdNtStudyTeachUpdate(stt_id);
            if (tdNtStudyTeachUpdate != null && tdNtStudyTeachUpdate.getStudy_state().equals("0")) {
                if (type == 1) {
                    tdNtStudyTeachUpdate.setStudy_state("6");
                    tdNtStudyTeachUpdate.setEnd_time(new Timestamp(System.currentTimeMillis()));
                    tdNtStudyTeachDao.updateTdNtStudyTeachCancel(tdNtStudyTeachUpdate);
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("取消成功");

                } else {
                    tdNtStudyTeachUpdate.setStudy_state("1");
                    tdNtStudyTeachUpdate.setTea_id(tea_id);
                    tdNtStudyTeachUpdate.setStart_time(new Timestamp(System.currentTimeMillis()));

                    tdNtStudyTeachDao.updateTdNtStudyTeach(tdNtStudyTeachUpdate);

                    TdNtTeacherState tdNtTeacherState = new TdNtTeacherState();
                    tdNtTeacherState.setTea_id(tdNtStudyTeachUpdate.getTea_id());
                    tdNtTeacherState.setState(Constants.Teacher.State.offline);
                    tdNtTeacherState.setState_order(Constants.Teacher.StateOrder.offline);
                    TdNtMemberDetailOrders tdNtMemberDetailOrders = tdNtMemberDao.findTdNtMemberDetailOrders(tdNtStudyTeachUpdate.getMemb_id());
                    MemcachedUtils.delete(tdNtMemberDetailOrders.getToken()+"nativetalk");
                    tdNtTeacherDao.updateTdNtTeacherState(tdNtTeacherState);
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("接单成功");
                    Map<String , List<TdNtCoursePictureList>> tdNtCoursePictureListMap = (Map<String , List<TdNtCoursePictureList>> )MemcachedUtils.get(MemcachedKey.tdNtCoursePictureListMap);
                    List<TdNtCoursePictureList> tdNtCoursePictureLists = tdNtCoursePictureListMap.get("" + tdNtStudyTeachUpdate.getCou_id());
                    List<TdNtCoursePictureListUrl> tdNtCoursePictureListUrls = new ArrayList<>();
                    for (int i = 0 ; i < tdNtCoursePictureLists.size(); i ++) {
                        TdNtCoursePictureListUrl tdNtCoursePictureListUrl = new TdNtCoursePictureListUrl();
                        tdNtCoursePictureListUrl.setImg_url(tdNtCoursePictureLists.get(i).getImg_url());
                        tdNtCoursePictureListUrls.add(tdNtCoursePictureListUrl);
                    }
                    if (version ==2) {
                        retInfo.setObj(tdNtCoursePictureLists);
                    } else {
                        retInfo.setObj(tdNtCoursePictureListUrls);
                    }
                    if (version >=3) {
                        //获取课程目录
                        Map<String, List<TdNtCourseCatalogEnglish>> CatalogEnglish = (Map<String , List<TdNtCourseCatalogEnglish>> )MemcachedUtils.get(MemcachedKey.tdNtCourseCatalogEnglishMap);
                        List<TdNtCourseCatalogEnglish> tdNtCourseCatalogEnglish = CatalogEnglish.get(""+tdNtStudyTeachUpdate.getCou_id());
                        //获取当前课程学习页数
                        TdNtMembCourseDetail tdNtMembCourse =new TdNtMembCourseDetail();
                        tdNtMembCourse.setCou_id(tdNtStudyTeachUpdate.getCou_id());
                        tdNtMembCourse.setMemb_id(tdNtStudyTeachUpdate.getMemb_id());
                        tdNtMembCourse = tdNtStudyTeachDao.findTdNtMembCourseDetail(tdNtMembCourse);
                        Map<String, Object> map = new HashMap<>();
                        if ("100".equals(tdNtStudyTeachUpdate.getCou_id().toString())){
                            map.put("video_switch",0);
                            map.put("course_flag",0);
                        }else{
                            map.put("video_switch", tdNtMemberDetailOrders.getVideo_switch());
                            map.put("course_flag",1);
                        }
                        for (int i = 0 ; i < tdNtCourseCatalogEnglish.size() ; i ++ ) {
                            tdNtCourseCatalogEnglish.get(i).setCata_name(tdNtCourseCatalogEnglish.get(i).getCata_english_name());
                        }
                        map.put("catalog",tdNtCourseCatalogEnglish);
                        if (tdNtMembCourse == null){
                            map.put("studySize", 1);
                        }else{
                            map.put("studySize", tdNtMembCourse.getStudy_page());
                        }
                        map.put("picture",tdNtCoursePictureLists);
                        map.put("student_channel", tdNtMemberDetailOrders.getToken());
                        retInfo.setObj(map);
                    }

                }

            } else {
                if (type == 1){
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("已经接单"));
                    TdNtMemberDetail tdNtMember = tdNtMemberDao.findTdNtMemberDetail(tdNtStudyTeachUpdate.getMemb_id());
                    Map<String, Object> result = new HashMap<>();
                    result.put("memb_name",tdNtMember.getMemb_name());
                    result.put("memb_head_portrait",tdNtMember.getMemb_head_portrait());
                    result.put("stt_id", stt_id);
                    TdNtTeacherIndex tdNtTeacherIndex =  tdNtTeacherDao.findTdNtTeacherIndex(tdNtStudyTeachUpdate.getTea_id());
                    result.put("tea_name", tdNtTeacherIndex.getTea_name());
                    result.put("tea_head_portrait", tdNtTeacherIndex.getTea_head_portrait());
                    Map<String , List<TdNtCoursePictureList>> tdNtCoursePictureListMap = (Map<String , List<TdNtCoursePictureList>> )MemcachedUtils.get(MemcachedKey.tdNtCoursePictureListMap);
                    result.put("course_pictures", tdNtCoursePictureListMap.get("" + tdNtStudyTeachUpdate.getCou_id()));
                    result.put("channel",tdNtTeacherIndex.getTea_invite_code());
                    result.put("recordKey", DynamicKey4Sample.getRecordKey(appID,tdNtTeacherIndex.getTea_invite_code(),ts, r, uid, expiredTs));
                    result.put("channelKey", DynamicKey4Sample.getChannelKey(appID,tdNtTeacherIndex.getTea_invite_code(),ts, r, uid, expiredTs));
                    result.put("ts", ts);
                    result.put("r", r);
                    result.put("uid", uid);
                    result.put("appID", appID);
                    result.put("expiredTs", expiredTs);
                    retInfo.setObj(result);
                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("STUDYTEACH_STATE.ERROR"));
                }

            }


        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }


    //用不到了  android竟然还在调用此接口
    public synchronized   RetInfo end(int stt_id, String version) {
        String logInfo = this.getClass().getName() + ":end:";
        logger.info("======" + logInfo + "begin======");
        Date nowDate = new Date();
        RetInfo retInfo = new RetInfo();
        try {
            Map<String , TsNtWebSiteConfIndex> tsNtWebSiteConfIndexMap = (Map<String , TsNtWebSiteConfIndex>)MemcachedUtils.get(MemcachedKey.tsNtWebSiteConfIndexMap);
            BigDecimal tea_amount = new BigDecimal(tsNtWebSiteConfIndexMap.get("24").getData_value());
            BigDecimal sutdy_amount = new BigDecimal(tsNtWebSiteConfIndexMap.get("25").getData_value());
            TdNtStudyTeachUpdate tdNtStudyTeachUpdate = tdNtStudyTeachDao.findTdNtStudyTeachUpdate(stt_id);
            if (tdNtStudyTeachUpdate !=null
                    && tdNtStudyTeachUpdate.getStudy_state().equals("1")){
                TdNtTeacherIndex tdNtTeacherIndex = tdNtTeacherDao.findTdNtTeacherIndex(tdNtStudyTeachUpdate.getTea_id());

                /**
                 * 计算教学价格  修改教学记录信息
                 */
                Long now = System.currentTimeMillis();
                Long teach_time = (now - tdNtStudyTeachUpdate.getStart_time().getTime())/1000;
                int month = new Integer((int) (teach_time/60));
                int tea_month = month;
                if ((teach_time%60) != 0) {
                    month = month + 1;
                }

                /**
                 * 判断用户是否在免费时段学习
                 */
                if (tsNtWebSiteConfIndexMap.get("9").getData_value().equals("0")) {
                    Date start_time = new Date(tdNtStudyTeachUpdate.getStart_time().getTime());
                    if (CommonUtil.isInDate(start_time,tsNtWebSiteConfIndexMap.get("10").getData_value(),
                            tsNtWebSiteConfIndexMap.get("11").getData_value())) {
                        Date end_time = new Date(now);
                        if (CommonUtil.isInDate(end_time,tsNtWebSiteConfIndexMap.get("10").getData_value(),
                                tsNtWebSiteConfIndexMap.get("11").getData_value())) {
                            month = 0;
                        } else {
                            //超过当前时间
                            month = CommonUtil.getMinute(new Date(end_time.getTime()),
                                    new Date(tdNtStudyTeachUpdate.getStart_time().getTime()),tsNtWebSiteConfIndexMap.get("11").getData_value());
                        }

                    }
                }
                if ((now - tdNtStudyTeachUpdate.getStart_time().getTime()) <= 10000 ) {
                    month = 0;
                }
                /**
                 * 查询用户余额及用户套餐
                 */
                Map<String , TsNtCourseInfoDetail> tsNtCourseInfoDetailMap = (Map<String , TsNtCourseInfoDetail> )MemcachedUtils.get(MemcachedKey.tsNtCourseInfoDetailMap);
                TsNtCourseInfoDetail tsNtCourseInfoDetail = tsNtCourseInfoDetailMap.get(tdNtStudyTeachUpdate.getCou_id()+"");
                BigDecimal memb_banlance = tdNtMemberDao.findTdNtMemberBalabce(tdNtStudyTeachUpdate.getMemb_id());
                Map<String,Object> map = new HashMap<>();
                map.put("memb_id",tdNtStudyTeachUpdate.getMemb_id());
                map.put("cou_id",tsNtCourseInfoDetail.getCate_id());
                tdNtStudyTeachUpdate.setEnd_time(new Timestamp(now));
                tdNtStudyTeachUpdate.setStudy_time(month);
                tdNtStudyTeachUpdate.setStudy_state("3");
                tdNtStudyTeachUpdate.setTea_study_time(tea_month);
                tdNtStudyTeachUpdate.setTea_study_amount(tea_amount.multiply(new BigDecimal(tea_month)));

                TdNtMembSetmealDetail tdNtMembSetmealDetail = tdNtMembSetmealDao.findTdNtMembSetmealDetail(map);

                if (tdNtMembSetmealDetail != null && (tdNtMembSetmealDetail.getSurplus_time()+1)>=month){
                    if ((tdNtMembSetmealDetail.getSurplus_time()+1)==month) {
                        month = tdNtMembSetmealDetail.getSurplus_time();
                        tdNtStudyTeachUpdate.setStudy_time(month);
                    }
                    /**
                     * 更新套餐
                     */
                    tdNtMembSetmealDetail.setSurplus_time(tdNtMembSetmealDetail.getSurplus_time() - month);
                    if (tdNtMembSetmealDetail.getSet_limit() == 1 && tdNtMembSetmealDetail.getSurplus_time() <= 0) {
                        tdNtMembSetmealDetail.setState(3);
                        tdNtMembSetmealDetail.setEnd_time(new Timestamp(now));
                    }
                    tdNtMembSetmealDao.updateTdNtMembSetmealDetail(tdNtMembSetmealDetail);
                    /**
                     * 添加套餐使用记录
                     */
                    TdNtSetmealUseHisInsert tdNtSetmealUseHisInsert = new TdNtSetmealUseHisInsert();
                    tdNtSetmealUseHisInsert.setEnd_time(tdNtStudyTeachUpdate.getEnd_time());
                    tdNtSetmealUseHisInsert.setUse_time(tdNtStudyTeachUpdate.getStart_time());
                    tdNtSetmealUseHisInsert.setSet_id(tdNtMembSetmealDetail.getSet_id());
                    tdNtSetmealUseHisInsert.setStt_id(tdNtStudyTeachUpdate.getStt_id());
                    tdNtSetmealUseHisInsert.setUser_duration(month);
                    tdNtSetmealUseHisDao.insertTdNtSetmealUseHis(tdNtSetmealUseHisInsert);

                    tdNtStudyTeachUpdate.setStudy_amount(tdNtMembSetmealDetail.getMinute_amout().multiply(new BigDecimal(month)));

                } else {
                    tdNtStudyTeachUpdate.setStudy_amount(sutdy_amount.multiply(new BigDecimal(month)));
                    BigDecimal studentChangeAmount = sutdy_amount.multiply(new BigDecimal(month));
                    BigDecimal memb_banlance_back = memb_banlance.subtract(studentChangeAmount);
                    if (memb_banlance_back.compareTo(new BigDecimal("-2"))==0) {
                        memb_banlance_back = new BigDecimal("0");
                    }
                    /**
                     * 添加用户资金变动记录
                     */
                    TdNtMembFoundChangeInset tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();
                    tdNtMembFoundChangeInset.setMemb_id(tdNtStudyTeachUpdate.getMemb_id());
                    tdNtMembFoundChangeInset.setMfchg_back_amount(memb_banlance_back);
                    tdNtMembFoundChangeInset.setMfchg_change_amount(studentChangeAmount);
                    tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(nowDate));
                    tdNtMembFoundChangeInset.setMfchg_front_amount(memb_banlance);
                    tdNtMembFoundChangeInset.setMfchg_change_name("呼叫老师（闲聊）");
                    tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                    tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                    tdNtMembFoundChangeInset.setType(Constants.ChargeType.call_teacher_free_talk_code);
                    tdNtMembFoundChangeInset.setMfchg_number(CommonUtil.getOrderNub());
                    tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);
                    /**
                     * 修改用户余额
                     */
                    TdNtMemberInvite tdNtMemberInvite = new TdNtMemberInvite();
                    tdNtMemberInvite.setMemb_id(tdNtStudyTeachUpdate.getMemb_id());
                    tdNtMemberInvite.setMemb_balance(memb_banlance_back);
                    tdNtMemberDao.updateTdNtMemberBalance(tdNtMemberInvite);
                }
                /**
                 * 更新学习记录
                 */
                tdNtStudyTeachDao.updateTdNtStudyTeachEnd(tdNtStudyTeachUpdate);
                /**
                 * 添加教师资金变动记录
                 */
                BigDecimal changeAmount = tea_amount.multiply(new BigDecimal(tea_month));
                TdNtTeaFoundChangeInsert tdNtTeaFoundChangeInsert = new TdNtTeaFoundChangeInsert();
                tdNtTeaFoundChangeInsert.setState("2");
                tdNtTeaFoundChangeInsert.setTea_id(tdNtStudyTeachUpdate.getTea_id());
                tdNtTeaFoundChangeInsert.setTfchg_account(new BigDecimal("0"));
                tdNtTeaFoundChangeInsert.setTfchg_change_amount(changeAmount);
                tdNtTeaFoundChangeInsert.setTfchg_back_amount(tdNtTeacherIndex.getTea_balance().add(changeAmount));
                tdNtTeaFoundChangeInsert.setTfchg_change_month(CommonUtil.getMonth(nowDate));
                tdNtTeaFoundChangeInsert.setTfchg_change_type("1");
                tdNtTeaFoundChangeInsert.setTfchg_counter_fee(new BigDecimal("0"));
                tdNtTeaFoundChangeInsert.setTfchg_front_amount(tdNtTeacherIndex.getTea_balance());
                tdNtTeaFoundChangeInsert.setTfchg_number(CommonUtil.getOrderNub());
                tdNtTeaFoundChangeInsert.setTfchg_change_name("Freetalk");
                tdNtTeaFoundChangeInsert.setType(0);
                tdNtTeaFoundChangeDao.insertTdNtTeaFoundChangeInsert(tdNtTeaFoundChangeInsert);
                /**
                 * 修改教师余额 及教学时间
                 */
                tdNtTeacherIndex.setTea_balance(tdNtTeaFoundChangeInsert.getTfchg_back_amount());
                tdNtTeacherIndex.setTea_times(tdNtTeacherIndex.getTea_times() + tea_month);
                tdNtTeacherIndex.setTea_id(tdNtStudyTeachUpdate.getTea_id());
                tdNtTeacherIndex.setTea_total_balance(tdNtTeacherIndex.getTea_total_balance().add(tdNtTeaFoundChangeInsert.getTfchg_change_amount()));
                tdNtTeacherIndex.setTea_total_times(tdNtTeacherIndex.getTea_total_times()+tea_month);
                tdNtTeacherDao.updateTdNtTeacherIndex(tdNtTeacherIndex);
                TdNtTeacherState tdNtTeacherState = new TdNtTeacherState();
                tdNtTeacherState.setTea_id(tdNtStudyTeachUpdate.getTea_id());
                tdNtTeacherState.setState(Constants.Teacher.State.online);
                tdNtTeacherState.setState_order(Constants.Teacher.StateOrder.online);
                tdNtTeacherDao.updateTdNtTeacherState(tdNtTeacherState);




                /**
                 * 添加或者更新用户学习课程记录
                 */

                if (!version.equals("1")) {
                    if (MemcachedUtils.get(stt_id+"") != null) {
                        String size = (String)MemcachedUtils.get(stt_id+"");
                        Integer study_page =  Integer.valueOf(size);
                        TdNtMembCourseDetail tdNtMembCourseDetail =
                                tdNtMembCourseDao.findTdNtMembCourseDetail(tdNtStudyTeachUpdate.getMemb_id(),tdNtStudyTeachUpdate.getCou_id());

                        if (tdNtMembCourseDetail != null ) {
                            if (tdNtMembCourseDetail.getState().equals("2")){
                                TdNtMembCourseDetail membCourseDetail = new TdNtMembCourseDetail();
                                membCourseDetail.setCou_id(tdNtStudyTeachUpdate.getCou_id());
                                membCourseDetail.setMemb_id(tdNtStudyTeachUpdate.getMemb_id());
                                membCourseDetail.setState("1");
                                membCourseDetail.setStudy_page(study_page);
                                tdNtMembCourseDao.insertTdNtMembCourse(membCourseDetail);
                            } else {
                                Map<String , List<TdNtCoursePictureList>> tdNtCoursePictureListMap = (Map<String , List<TdNtCoursePictureList>> )MemcachedUtils.get(MemcachedKey.tdNtCoursePictureListMap);
                                List<TdNtCoursePictureList> tdNtCoursePictureLists = tdNtCoursePictureListMap.get("" + tdNtStudyTeachUpdate.getCou_id());
                                tdNtMembCourseDetail.setEnd_time(new Timestamp(System.currentTimeMillis()));
                                tdNtMembCourseDetail.setStudy_page(study_page);
                                if (tdNtCoursePictureLists.size() == study_page) {
                                    tdNtMembCourseDetail.setState("2");
                                    /**
                                     * 更新课程学习人数
                                     */
                                    Map<String, Object> updateCourse = new HashMap<>();
                                    tsNtCourseInfoDetail.setStudy_size(tsNtCourseInfoDetail.getStudy_size()+1);
                                    updateCourse.put("cou_id",tdNtStudyTeachUpdate.getCou_id());
                                    updateCourse.put("study_size",tsNtCourseInfoDetail.getStudy_size());
                                    tsNtCourseInfoDao.updateTsNtCourseInfoStudySize(updateCourse);
                                }
                                tdNtMembCourseDao.updateTdNtMembCourse(tdNtMembCourseDetail);
                            }
                        } else {
                            TdNtMembCourseDetail membCourseDetail = new TdNtMembCourseDetail();
                            membCourseDetail.setCou_id(tdNtStudyTeachUpdate.getCou_id());
                            membCourseDetail.setMemb_id(tdNtStudyTeachUpdate.getMemb_id());
                            membCourseDetail.setState("1");
                            membCourseDetail.setStudy_page(study_page);
                            tdNtMembCourseDao.insertTdNtMembCourse(membCourseDetail);

                        }
                    }
                }

                TdNtMemberStudyTimes tdNtMemberStudyTimes =
                        tdNtMemberDao.findTdNtMemberStudyTimes(tdNtStudyTeachUpdate.getMemb_id());
                tdNtMemberStudyTimes.setTotal_study_times(tdNtMemberStudyTimes.getTotal_study_times() + month);
                tdNtMemberDao.updateTdNtMemberStudyTimes(tdNtMemberStudyTimes);
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("结束成功");

            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip(ValidationMessages.getValue("TIPAUTHORERROR"));
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }


}
